package com.heima.search.listen;


import com.heima.common.exception.CustException;
import com.heima.feigns.ApAuthorFeign;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    ApAuthorFeign apAuthorFeign;
    @Autowired
    ArticleSearchService articleSearchService;

    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void addArticle(String articleId){
        log.info("接收文章上架消息 接收到添加文章到索引库消息==> {}",articleId);
        ResponseResult<SearchArticleVO> articleVoResult = apAuthorFeign.findArticle(Long.valueOf(articleId));
        if (!articleVoResult.checkCode()) {
            log.error("远程调用查询失败:原因: {}",articleVoResult.getErrorMessage());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,articleVoResult.getErrorMessage());
        }
        SearchArticleVO searchArticleVo = articleVoResult.getData();
        if (searchArticleVo==null){
            log.error("远程调用 为查询到文章信息 文章id: {}",articleId);

            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到文章信息");
        }
        articleSearchService.saveArticle(searchArticleVo);
        log.info("成功更新索引信息   add: {}",articleId);

    }
    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void removeArticle(String articleId){
        log.info("接收文章下架消息 接收到删除索引库文章消息==> {}",articleId);
        try {
            articleSearchService.deleteArticle(articleId);
            log.info("成功更新索引信息   delete: {}",articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}",articleId,e.getMessage());
        }
    }
}
